<?php
namespace Destroyer\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

use Destroyer\Models\Role;
use Destroyer\Http\Requests\RoleCreateRequest;
use Destroyer\Http\Requests\RoleUpdateRequest;

class RoleController extends Controller
{

	public function index(Request $request)
	{
		$validated = $request->validate([
			// 分页
			'page'      => 'sometimes|integer|min:1',
			'page_size' => 'sometimes|integer|between:1,100',
			// 排序
			'sorter'           => 'sometimes|array:field,direction',
			'sorter.direction' => 'sometimes|string|in:ascend,descend',
			'sorter.field'     => 'sometimes|string|in:id,sort',
		]);

		$query = Role::query();

		// 排序
		$field = Arr::get($validated, 'sorter.field', 'sort');
		$direction = Arr::get($validated, 'sorter.direction', 'ascend');
		$query->orderBy($field, substr($direction, 0, -3));

		// 查询
		$page_size = $request->input('page_size');
		$models = $query->paginate($page_size);

		return response()->admin($models);
	}

	public function show(Request $request, $id)
	{
		$model = Role::findOrFail($id);

		return response()->admin($model);
	}

	public function store(RoleCreateRequest $request)
	{
		$validated = $request->validated();

		$model = Role::create($validated);

		return response()->admin($model);
	}

	public function update(RoleUpdateRequest $request, $id)
	{
		$validated = $request->validated();

		$model = Role::findOrFail($id);
		$updated = $model->update($validated);

		return response()->admin($model);
	}

	public function destroy(Request $request, $id)
	{

	}

	public function select(Request $request)
	{
		$models = Role::select('name as label', 'id as value')
					->limit(100)
					->get();

		return response()->admin($models);
	}
}
